<template>
  <!-- 发布资讯页面 -->
  <div>
    <el-form :model="form" ref="myForm" lable-width="100px">
      <el-form-item lable="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item lable="分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择栏目" clearable>
          <el-option
            v-for="item in categoryData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="正文" prop="content">
        <el-input type="textarea" v-model="form.content"></el-input>
      </el-form-item>
      <el-form-item lable="封面" prop="cover">
        <el-upload
          class="avatar-uploader"
          :action="uploadFileURL"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="form.cover" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="goBack">返回</el-button>
        <el-button @click="submitForm()">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { saveArticle } from '@/api/article'
import { queryCateConsult } from '@/api/infoCategory'
import { uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      categoryData: [],
      form: {},
      imageUrl:'',
      uploadFileURL,
    };
  },
  computed: {},
  methods: {
    // 获取所有栏目名称
    async getColumn() {
      for (const key in this.params) {
        if (!this.params[key]) {
          delete this.params[key]
        }
      }
      const res = await queryCateConsult(this.params)
      this.categoryData = res.data
    },
    // 图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.cover = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 保存
    async submitForm(){
      let res = await saveArticle(this.form);
      this.$notify({
        type:'success',
        message:res.message
      })
      this.$router.go(-1)
    },
    // 返回
    goBack(){
      this.$router.go(-1);
    }
  },
  created() {
    this.getColumn();
  },
  mounted() {},
};
</script>
<style scoped>
</style>